package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.ActiveModifications;
import org.akomantoso.core.data.AnalysisElement;
import org.akomantoso.core.data.Parliamentary;
import org.akomantoso.core.data.PassiveModifications;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class AnalysisUtil {

	private AnalysisUtil() {
	}

	private static final Map<String, Instantiator<AnalysisElement>> MAP;

	public static void read(Input in, List<AnalysisElement> elements) throws IOException {
		AnalysisElement element = null;
		final String localName = in.getLocalName();
		int eventType;
		while (true) {
			eventType = in.readNext();
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				elements.add(element = instantiate(in.getLocalName()));
				element.readExternal(in);
				break;
			case InputConstants.END_ELEMENT:
				if (localName.equals(in.getLocalName())) {
					return;
				}
			}
		}
	}

	static AnalysisElement instantiate(String elementName) {
		final Instantiator<AnalysisElement> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported for AnalysisElement ?!?");
		}
		return instatiator.instantiate();

	}

	static {

		Map<String, Instantiator<AnalysisElement>> temp = new HashMap<String, Instantiator<AnalysisElement>>();

		// activeModifications
		temp.put(ActiveModifications.ELEMENT, new Instantiator<AnalysisElement>() {
			public ActiveModifications instantiate() {
				return new ActiveModifications();
			}
		});

		// passiveModifications
		temp.put(PassiveModifications.ELEMENT, new Instantiator<AnalysisElement>() {
			public PassiveModifications instantiate() {
				return new PassiveModifications();
			}
		});

		// parliamentary
		temp.put(Parliamentary.ELEMENT, new Instantiator<AnalysisElement>() {
			public Parliamentary instantiate() {
				return new Parliamentary();
			}
		});

		MAP = Collections.unmodifiableMap(temp);
	}
}
